package com.tedu.dao.impl;

import com.tedu.dao.DeptDao;
import com.tedu.entry.Dept;
import com.tedu.util.JDBCUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Author：毕龙
 * Date: 2023/7/28 10:23
 */
public class DeptDaoImpl  implements DeptDao {
    @Override
    public List<Dept> selectAllDept() {
        Connection conn = null;
        PreparedStatement pstm = null;
        ResultSet rs = null;
        ArrayList<Dept> list = new ArrayList<>();
        try {
            //1.获取链接
            conn = JDBCUtil.getConnection();

            //2.执行sql
            String sql = "select * from dept ";
            pstm = conn.prepareStatement(sql);
            rs = pstm.executeQuery();

            //3.处理查询结果
            while (rs.next()){
                Dept dept = new Dept();
                dept.setId(rs.getInt(1))
                        .setName(rs.getString(2));
                list.add(dept);
            }

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {

            //4.释放资源
            JDBCUtil.release(rs,pstm);
            JDBCUtil.release(conn);
        }

        return list;
    }
}
